var nuo = {
    // callback define
    callback : {
    },
    // ui defined
    ui : {
    }
};
nuo.require = function(a, d, e, c) {
    if ( typeof window[a] == 'undefined') {
        window[a] = 0
        if (a == 'js') {
            $.getScript($config.staticUrl + b, c);
        } else {
            $.getStyle($config.staticUrl + b, c);
        }
    } else {
        c();
    }
};
nuo.isEmpty = function(a) {
    return $.isEmptyObject(a);
}
nuo.newId = function() {
    var seek = '123456789zxcvbnmadfghjklqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM', max, ret = '', max = seek.length;
    for (var i = 0; i < 6; ++i) {
        ret += seek.charAt(max * Math.random());
    }
    return 'ui-' + ret;
};
nuo.tooltip = function(t) {
    var text = t.attr('tooltip'), pos, dom = null, text;
    if (nuo.isEmpty(text))
        return;
    dom = $('<div class="uiFlyLayer uiTooltipLayer"></div>').appendTo('body');
    dom.html('<div class="uiTooltipOuter"><div class="uiTooltipStage"></div><div class="uiTooltipArrow"><div></div></div></div>');

    pos = t.offset();
    var w = t.width();
    dom.css({
        left : pos.left + Math.ceil(w / 2),
        top : pos.top
    }).find('.uiTooltipStage').html(text);
    function hide() {
        dom.remove();
    }


    dom.addClass('active');
    t.bind('mouseout', hide);
}
sYNDirection = 'ltr';
var CardHover = {
    isShowing : 0,
    isMouseOver : 1,
    ele : 0,
    href : '',
    data : '',
    uri : '',
    timeoutOpen : 300,
    timeoutClose : 300,
    maxHeightOfPopup : 150,
    mouseOverTimeoutId : 0,
    timeoutId : 0,
    cached : {
    },
    dir : {
        cx : 0,
        cy : 0
    },
    box : null,
    data : '',
    flush : function() {
        CardHover.cached = {};
    },
    check : function(t, evt) {
        var uri = t.attr('uri'), data = t.attr('data-id');
        if (nuo.isEmpty(data)) {
            return;
        }
        CardHover.data = data;
        CardHover.uri = uri;
        CardHover.ele = t;
        CardHover.href = '';
        CardHover.data = data;

        if (CardHover.timeoutId) {
            try {
                window.clearTimeout(CardHover.timeoutId);
                CardHover.timeoutId = 0;
            } catch(e) {

            }
        }

        $(t).mouseleave(function(evt) {
            CardHover.resetTimeout(0)
        });

        CardHover.timeoutId = 0;
        CardHover.isRunning = 0;
        CardHover.dir = {
            'cx' : evt.clientX,
            'cy' : evt.clientY
        };
        CardHover.timeoutId = window.setTimeout(CardHover.request, 500);
    },
    loading : function() {
        var box = CardHover.getBox();
        box.find('.uiCardHoverStage').html('<div class="uiCardhoverContent">Loading ...</div>');
    },
    request : function() {

        var k = CardHover.data;

        if (!k) {
            return;
        }

        CardHover.timeoutId = 0;

        if (!nuo.isEmpty(CardHover.cached[k])) {
            return CardHover.showPopup(CardHover.cached[k]);
        }

        $.getJSON(CardHover.uri, {
            'data-id' : k
        }, CardHover.showPopup);

        //CardHover.loading();

        //CardHover.resetPosition(1);
    },
    resetTimeout : function($flag) {
        var card = CardHover;
        card.isMouseOver = $flag;
        if (card.mouseOverTimeoutId) {
            try {
                window.clearTimeout(card.mouseOverTimeoutId);
                card.mouseOverTimeoutId = 0;
                if (card.timeoutId) {
                    try {
                        window.clearTimeout(card.timeoutId);
                        card.timeoutId = 0;
                    } catch(e) {
                    }
                }
            } catch(e) {
            }
        }
        if ($flag == 0) {
            card.data = 0;
            card.mouseOverTimeoutId = window.setTimeout(card.hide, card.timeoutClose);
        }

    },
    hide : function() {
        CardHover.isShowing = 0;
        box = CardHover.getBox();
        box.hide();
    },
    resetPosition : function(flag) {
        CardHover.isShowing = 1;
        var box = CardHover.getBox();
        var ele = CardHover.ele;
        if (!ele) {
            return;
        }
        var offset = ele.offset();

        var size = {
            w : $(ele).width(),
            h : $(ele).height()
        };

        var left = 0, top = 0;

        if (CardHover.dir.cy > 150) {
            top = offset.top;
            box.removeClass('uiCardHoverDown').addClass('uiCardHoverUp');
        } else {
            top = offset.top + size.h;
            box.removeClass('uiCardHoverUp').addClass('uiCardHoverDown');
        }

        if (sYNDirection == 'ltr') {
            if ($(window).width() - CardHover.dir.cx > 425) {
                box.removeClass('uiCardHoverLeft').addClass('uiCardHoverRight');
                left = size.w > 245 ? CardHover.dir.cx : offset.left;
            } else {
                box.removeClass('uiCardHoverRight').addClass('uiCardHoverLeft');
                left = size.w > 245 ? CardHover.dir.cx : (offset.left + size.w);
            }
        } else {
            // right to left
            if (CardHover.dir.cx < 376) {
                box.removeClass('uiCardHoverLeft').addClass('uiCardHoverRight');
                left = size.w > 245 ? CardHover.dir.cx : offset.left;
            } else {
                left = size.w > 245 ? CardHover.dir.cx : (offset.left + size.w);
                box.removeClass('uiCardHoverRight').addClass('uiCardHoverLeft');
            }
        }

        box.css({
            'left' : left,
            'top' : top
        });

        if (flag) {
            box.show();
        }
    },
    showPopup : function(json) {
        var k = json.data_id;
        CardHover.cached[k] = json;
        if (k != CardHover.data) {
            return CardHover.closePopup();
        }
        CardHover.resetPosition(1);
        var box = CardHover.getBox();
        box.find('.uiCardHoverStage').html(json.html);
        box.show();
    },
    getBox : function() {
        if (CardHover.box) {
            return CardHover.box;
        }
        var dom = $('<div class="uiCardHoverLayer"></div>').appendTo('body');
        var html = '<div class="uiCardHoverOuter"><div class="uiCardHoverStage"></div><div class="uiCardHoverArrow"><div></div></div></div>';
        dom.html(html).bind('mouseover', function(evt) {
            CardHover.resetTimeout(1);
        }).bind('mouseout', function(evt) {
            CardHover.resetTimeout(0);
        });
        return CardHover.box = dom;
    }
};

nuo.cardhover = function(t, evt) {
    CardHover.check(t, evt);
}

nuo.jscript = function(t) {
    var cb = t.attr('aria-cb');
    if(nuo.isEmpty(cb)){
        return ;
    }
    cb =  cb.split('.');
    nuo.callback[cb[0]][cb[1]](t);
}
nuo.placeholder = function() {
    var t = $(this), text = t.attr('placeholder'), binded = t.attr('binded');
    if (text == null || text == '') {
        return;
    }

    if (t.val() == text) {
        t.val('');
    }

    if (nuo.isEmpty(binded)) {
        function changed() {
            if (t.val() == '') {
                t.val(text);
            }
        }


        t.attr('binded', 1);
        t.bind('change', changed);
    }
}
/**
 * auto complete should be lazy load and ready for multiple instance if you want to support multiple later.
 */
nuo.autocomplete = function() {
    var t = $(this), dom, content, ul, content = null, pos = {
    }, height = {
    }, atname = "autocomplete-id", idname = "autocomplete-id", idkey = t.attr(atname), data, url = '/v4/fox/search', html;
    /**
     * callback function from remote content.
     */
    function cb() {
    }

    function hide() {
        dom.hide();
    }

    function update(json) {
        content.html(json.html);
    }

    function request() {
        data = t.val();
        $.getJSON(url, {
            q : data
        }, update);
    }

    function loading() {
        content.html('<div class="uiLoading"> loading ... </div>');
    }

    if (idkey) {
        dom = $('#' + idkey);
    } else {
        idkey = nuo.newId();
    }
    if (dom == null || dom.length == 0) {
        dom = $('<div class="uiFlyLayer uiFlyAc"><div class="uiFlyOuter"><div class="uiFlyContent"></div></div></div>');
        dom.attr('id', idkey).appendTo('body:first');
        t.attr(idname, idkey);
    }

    content = dom.find('.uiFlyContent:first');

    dom.show();

    pos = t.offset();

    height = t.height();

    dom.css({
        left : pos.left,
        top : pos.top + height
    });

    t.bind('change', request).bind('keyup', request);
}
/**
 * singleton
 * @param {Object} a
 */
nuo.fbox = function(ele) {
    var loading = '<div class="uiFboxLoading">Loading ...</div>';
    var content = '<div class="uiFboxLayer"><div class="uiFboxOuter"><div class="uiFboxStage"></div></div></div></div>';
    var dom = '<div class="uiFixMashLayer"></div>';
    var pos, url, counter = 1, attrname = 'fbox';

    //ct <div class="uiFboxHeader"></div><div class="uiFboxContent"></div><div class="uiFboxFooter">
    dom = $(dom).appendTo('body').html(content);

    url = ele.attr('href');

    url = url.replace(/#.*$/g, '');

    if (url.indexOf('?') > -1) {
        url = url.replace('?', '?format=fbox&');
    } else {
        url += '?format=fbox&';
    }

    console.log(url);

    content = dom.find('.uiFboxStage');

    content.html(loading);

    function update(html) {
        content.html(html);
    }


    dom.bind('click', function(evt) {
        if (--counter < 1) {
            //dom.remove();
        }
    });
    dom.find('.uiFboxLayer').bind('click', function(evt) {
        counter = 2;
    });
    $.get(url, '', update);
}

nuo.fboxClose = function() {
    $('.uiFixMashLayer:last').remove();
}
nuo.refresh = function() {
    document.location.href = document.location.href;
}

nuo.toggle = function(t, evt) {
    var at = 'toggle-id', id = t.attr(at), cb = t.attr('aria-cb'), dom = null;

    if (t.hasClass('clicked')) {
        return;
    }

    if ($.isEmptyObject(id)) {
        id = nuo.newId();
        dom = t.closest('.uiToggleWrapper').find('.uiToggleFlyout');
        dom.attr('id', id);
        t.attr(at, id);
    } else {
        dom = $('#' + id);
    }

    t.addClass('clicked');
    dom.addClass('active');

    function hide(evt) {
        var target = $(evt.target);
        if (dom && target.closest('#' + id).length == 0) {
            t.removeClass('clicked');
            dom.removeClass('active');
            $(document).unbind('click', hide);
        }
    }


    $(document).bind('click', hide);

    if (cb) {
        cb = cb.split('.');
        nuo.callback[cb[0]][cb[1]](t);
    }
}
/**
 * get data object from data-id attribute
 */
nuo.getDataObj = function(t) {
    var ar = t.attr('data-id').split('_'), obj = {
        'type' : ar[0],
        'id' : ar[1]
    };
    return obj;
}
nuo.callback.share = {
    open : function(t) {
    }
}
nuo.flyContext = function(ele) {
    var t = $(ele), pos, loading, pid = 0, atname = 'fly-context', idname = 'fly-context-id', idvalue = t.attr(idname), timeout = 20000, dom = null, width = height = 0, inner = false;
    if (nuo.isEmpty($(t).attr(atname))) {
        return;
    }
    function hide() {
        if (inner == false) {
            dom.remove();
            t.removeClass('active');
        }
    }

    function reg() {
        pid = window.setTimeout(hide, timeout);
    }

    function goIn() {
        inner = true;
    }

    function goOut() {
        inner = false;
    }

    function kreg() {
        if (pid) {
            window.clearTimeout(pid);
            pid = 0;
        }
    }

    if (idvalue) {
        dom = $('#' + idvalue);
    } else {
        idvalue = nuo.newId();
    }

    if (null == dom || dom.length == 0) {
        dom = $('<div id="' + idvalue + '" class="uiFlyLayer uiFlyContextLayer"><div class="uiFlyOuter"><div class="uiFlyContent"></div><div class="uiFlyArrow"><div></div></div></div></div>').appendTo('body:first');
        t.attr(idname, idvalue);
        //t.bind('mouseout',goIn).bind('mouseover',goOut);
        dom.bind('mouseout', goOut).bind('mouseover', goIn);
        $(document).bind('click', hide);
    }

    pos = t.offset();
    width = t.width();
    height = t.height();

    dom.css({
        left : pos.left + width,
        top : pos.top + height
    });

    loading = '<div class="uiFlyContextLoading">Loading <span tooltip="ly-trinh" > coloboration 1 </span>... </div>';

    dom.find('.uiFlyContent:first').html(loading);
    dom.show();
    t.addClass('active');
};
nuo.thbox = function() {
    var dom, ele, pos, size, content, loading = '<div class="uiFboxLoading">Loading ...</div>', html = '<div class="uiFixMashLayer"><div class="uiTheaterLayer"><div class="uiTheaterOuter"><div class="uiTheaterContent"></div></div></div></div>';
    dom = $(html).appendTo('body:first');
    content = dom.find('.uiTheaterContent:first');
    content.html(loading);

    url = 'http://namnv.younetco.com/v4/test/thbox.html';

    function update(html) {
        content.html(html);
    }


    $.getJSON(url, '', update);
};

nuo.nothing = function() {
}

nuo.cancel = function(ele, url) {
    if ($(ele).closest('.uiFixMashLayer').length) {
        $(ele).closest('.uiFixMashLayer').remove();
    } else {
        if (nuo.isEmpty(url)) {
            url = window.location.href + '?';
        }
        var parts = url.split('?');
        // process url from slag.
        var ar = url.split('/');
        ar.pop();
        url = ar.join('/') + '?' + parts[1];
        window.location.href = url;
    }

}

nuo.flashMsg = function(msg) {
    var dom, content, id = '#uiMessage', html = '<div class="uiFixLayer" id="uiMessage"><div class="uiMessageLayer"><div class="uiMessageOuter"><div class="uiMessageContent"></div></div></div></div>'
    dom = $(id);
    if (dom.length == 0) {
        $(html).appendTo('#site');
        dom = $(id);
    }
    content = dom.find('.uiMessageContent');
    content.html(msg);
    dom.fadeIn();
    function hide() {
        dom.fadeOut(4000);
    }
    setTimeout(hide, 3000);
}
nuo.async = function(t) {
    var ele = $(t);
    var cb = '';
    var data = ele.serialize();
    var ar = t.attr('aria-cb');
    if (!nuo.isEmpty(ar)) {
        ar = ar.split('.')
        cb = nuo.callback[ar[0]][ar[1]];
    } else {
        cb = function(json) {
            console.log(json);
            if (json.jscript) {
                eval(json.jscript);
            }
            if (!json.html_id) {
                t.html(json.html);
            } else {
                $(json.html_id).html(json.html);
            }
        }
    }
    ele.find('.uiIconSmallIndicator').removeClass('uiHidden');
    
    $.post(ele.attr('action'), data, function(json) 
    {
        ele.find('.uiIconSmallIndicator').addClass('uiHidden');
        cb(json);
    }, 'json');
}
nuo.commentComposer = function(t) {
    if (t.val() == t.attr('placeholder')) {
        t.val('');
    }
    if (t.attr('typeahead-init') != 1) {
        Typeahead.init(t, {
            'minHeight' : 20,
            'onSubmit' : function(input) {
                input.closest('form').trigger('submit');
            }
        });
    }
}

nuo.postComposer = function(t) {
    if (t.val() == t.attr('placeholder')) {
        t.val('');
    }
    if (t.attr('typeahead-init') != 1) {
        Typeahead.init(t, {
            'minHeight' : 50,
            'onParseLink' : nuo.callback.link.parse
        });
    }
}
var CrapImg = {
    img : null,
    ele : null,
    imgSize : {
        w : 0,
        h : 0
    },
    init : function(url) {
        var crap = this;
        $('.uiCrapImg').html('');
        var img = crap.img = new Image;
        img.src = url;
        img.onload = function() {
            crap.imgSize = {
                w : this.width,
                h : this.height
            };
            crap.open(this);
            crap.resize();
        }
    },
    getCntSize : function() {
        var cnt = $('.photoCover');
        return {
            w : cnt.width(),
            h : cnt.height()
        };
    },
    open : function(img) {
        var crap = CrapImg, ele = crap.ele = $('<img></img>');
        ele.attr('src', img.src).addClass('uiHidden');
        $('.uiCrapImg').html(ele);
    },
    resize : function() {
        // resize element of object by decalled.
        var crap = CrapImg;
        var size1 = crap.getCntSize();
        var size2 = crap.imgSize;
        var s1 = size1.w / size2.w;
        var s2 = size1.h / size2.h;
        var h  =  size2.h > size1.h ? size1.h: size2.h;
        var w  =  h/size2.h* size2.w;
        
        if(w > size2.w)
        {
            w =  size2.w;
            h = w/size2.w * size2.h;    
        }
        
        var left = Math.floor((size1.w - w)/2);
        var top = Math.floor((size1.h - h)/2)
        
        crap.ele.attr('width',w).attr('height',h);
        $('.uiCrapImg').css({left:left,top:top});
                                                
        // show img.
        crap.ele.removeClass('uiHidden');
    }
} 